package com.leesche.zcsp.node.app.v1.controller.individual;

import com.leesche.zcsp.node.app.v1.timer.PhoneCodeCacheTimer;
import com.leesche.zcsp.node.app.v1.timer.VaildPhone;
import com.leesche.zcsp.node.app.v1.vo.BankCard;
import com.leesche.zcsp.node.app.v1.vo.VerifyResult;
import com.leesche.zcsp.node.communication.service.SmsService;
import com.leesche.zcsp.node.utils.security.QEncodeUtil;
import com.leesche.zcsp.node.utils.web.SessionManager;
import com.leesche.zcsp.node.utils.web.filemanager.FileManager;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.controller.template.UserTemplate;
import com.leesche.zcsp.node.web.model.*;
import com.leesche.zcsp.node.web.service.SysAuditPersonService;
import com.leesche.zcsp.node.web.service.SysNoticeService;
import com.leesche.zcsp.node.web.service.SysUserBalanceService;
import com.leesche.zcsp.node.web.service.SysUserBankCardService;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.service.impl.data.writ.AddBankCardCommand;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.UserGroup;
import com.leesche.zcsp.node.web.vo.UserInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Jerry Chan
 * @version V1.0
 * @Title: node
 * @Package com.leesche.zcsp.node.web.controller.wechat.individual
 * @Description:( 微信栏目"我的"控制器)
 * @date 2016年10月19日 12:14
 */
@Controller
@RequestMapping("/app/v1/indivdual")
public class AppIndivdualController extends UserTemplate {

    private static final Logger logger = Logger.getLogger(AppIndivdualController.class);

    @Autowired
    private SmsService smsService;

    @Autowired
    private PrivilegeService privilegeService;

    @Autowired
    private SysUserBalanceService sysUserBalanceService;

    @Autowired
    private SysNoticeService sysNoticeService;

    @Autowired
    private SysUserBankCardService sysUserBankCardService;

    @Autowired
    private SysAuditPersonService sysAuditPersonService;


    private String errorstr = "ERROR:";

    /**
     * @Title: showFooterContent()
     * @Description: TODO(获取用户自定义底部文字)
     * @author Jerry Chan
     * @date 2016/12/1 17:27
     */
    @ResponseBody
    @RequestMapping(value = "showfootcontent", method = RequestMethod.POST)
    public Map<String, Object> showFooterContent() {
        try {
            Long usreid = privilegeService.getCurrentPrincipalForApp().getUserid();
            QuerySysNoticeCondition condition = new QuerySysNoticeCondition();
            condition.setUserid(usreid);
            condition.setQueryAll(true);
            List<SysNoticeDto> noticeDtos = sysNoticeService.findListsByCondition(condition);

            if (noticeDtos == null || noticeDtos.size() <= 0) {
                return WebResult.failure("尚未添加底部文字，系统采用默认底部显示文字").toMap();
            }

            List<String> footerContents = new ArrayList<String>();
            for (SysNoticeDto noticeDto : noticeDtos) {
                footerContents.add(noticeDto.getButtomcontent());
            }
            return WebResult.success().put("data", footerContents).toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);;
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: addFooterContent(String footercontent)
     * @Description: TODO(新增底部文字)
     * @author Jerry Chan
     * @date 2016/12/1 17:06
     */
    @ResponseBody
    @RequestMapping(value = "addfootercontent", method = RequestMethod.POST)
    public Map<String, Object> addFooterContent(String footercontent) {

        try {
            Long usreid = privilegeService.getCurrentPrincipalForApp().getUserid();
            SysNotice notice = new SysNotice();
            notice.setButtomcontent(footercontent);
            notice.setUpdatetime(new Date());
            notice.setAdminid(usreid);
            notice.setUserid(usreid);

            if (addORUpdateNotice(notice) > 0) {
                return WebResult.success().toMap();
            } else {
                return WebResult.failure("编辑底部文字失败，请稍后重新编辑").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);;
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: delBankCard(Long cardid)
     * @Description: TODO(移除当前用户绑定的银行卡)
     * @author Jerry Chan
     * @date 2016/11/30 16:07
     */
    @ResponseBody
    @RequestMapping(value = "unbundingBankCard", method = RequestMethod.POST)
    public Map<String, Object> delBankCard(Long cardid) {
        try {
            Long usreid = privilegeService.getCurrentPrincipalForApp().getUserid();
            SysUserBankCardCriteria criteria = new SysUserBankCardCriteria();
            criteria.or().andUseridEqualTo(usreid).andCardidEqualTo(cardid);
            int result = sysUserBankCardService.deleteByCriteria(criteria);
            if (result > 0) {
                return WebResult.success().toMap();
            } else {
                return WebResult.failure("银行卡不存在").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);;
            return WebResult.failure("解绑失败").toMap();
        }
    }

    /**
     * @Title: changeBankCard
     * @Description: TODO(编辑用户已经绑定的银行卡)
     * @author Jerry Chan
     * @date 2016/11/30 16:55
     */
    @ResponseBody
    @RequestMapping(value = "editBankCard", method = RequestMethod.POST)
    public Map<String, Object> changeBankCard(AddBankCardCommand bankCard) {
        try {

            Long userid = privilegeService.getCurrentPrincipalForApp().getUserid();
            QuerySysUserBankCardCondition condition = new QuerySysUserBankCardCondition();
            condition.setUserid(userid);
            condition.setCardid(bankCard.getCardid());
            List<SysUserBankCard> cards = sysUserBankCardService.findUserBankCardByCondition(condition);
            if (cards == null || cards.size() < 1) {
                return WebResult.failure("尚未绑定银行卡").toMap();
            }

            String positiveSaveResult = null;
            String behindSaveResult = null;
            String licenseSaveResult = null;

            if (bankCard.getIdcrardimgpositive() != null) {
                //保存身份证正面照
                positiveSaveResult = FileManager
                        .saveImage(bankCard.getIdcrardimgpositive(), Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY);
                if (positiveSaveResult.contains(FileManager.ERRORSTR)) {
                    return WebResult.failure(positiveSaveResult.replace(FileManager.ERRORSTR, "")).toMap();
                } else {
                    positiveSaveResult = Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY + "/" + positiveSaveResult;
                }
            }

            if (bankCard.getIdcrardimgbehind() != null) {
                //保存身份证反面照
                behindSaveResult = FileManager
                        .saveImage(bankCard.getIdcrardimgbehind(), Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY);
                if (behindSaveResult.contains(FileManager.ERRORSTR)) {
                    return WebResult.failure(behindSaveResult.replace(FileManager.ERRORSTR, "")).toMap();
                } else {
                    behindSaveResult = Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY + "/" + behindSaveResult;
                }
            }

            if (bankCard.getBusinesslicense() != null) {
                licenseSaveResult = FileManager
                        .saveImage(bankCard.getBusinesslicense(), Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY);
                if (licenseSaveResult.contains(FileManager.ERRORSTR)) {
                    return WebResult.failure(licenseSaveResult.replace(FileManager.ERRORSTR, "")).toMap();
                } else {
                    licenseSaveResult = Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY + "/" + licenseSaveResult;
                }
            }

            SysUserBankCard card = new SysUserBankCard();
            card.setCardid(bankCard.getCardid());
            card.setAdminid(userid);
            card.setCardholder(bankCard.getCardholder());
            card.setBankcardnumber(bankCard.getBankcardnumber());
            card.setBankname(bankCard.getBankname());
            card.setMobile(bankCard.getMobile());
            card.setIdcard(bankCard.getIdcard());
            card.setPayunionbank(bankCard.getPayunionbank());
            card.setBankcountry(bankCard.getBankcountry());
            card.setBankprovince(bankCard.getBankprovince());
            card.setBankcity(bankCard.getBankcity());
            card.setBankofdeposit(bankCard.getBankofdeposit());
            card.setAccounttype(bankCard.getAccounttype());
            card.setBussinseclearingbank(bankCard.getBussinseclearingbank());
            card.setClearingcycle(bankCard.getClearingcycle());
            card.setCapitalclearingtype(bankCard.getCapitalclearingtype());
            card.setUpdatetime(new Date());
            card.setIdcrardimgpositive(positiveSaveResult);
            card.setIdcrardimgbehind(behindSaveResult);
            card.setBusinesslicense(licenseSaveResult);
            card.setCardconfirmed(0);//卡号进入从新审核流程
            int result = sysUserBankCardService.updateByPrimaryKeySelective(card);

            if (result > 0) {

                //进件受理通知(给客户)
                smsService.giveInfoAcceptSMS(card.getMobile(), card.getCardholder());
                //进件受理通知(给审核员)
                List<SysAuditPersonDto> personDtos = sysAuditPersonService
                        .findListsByCondition(new QuerySysAuditPersonCondition());
                if (personDtos != null && personDtos.size() > 0) {
                    List<String> mobiles = new ArrayList<String>();
                    for (SysAuditPersonDto dto : personDtos) {
                        mobiles.add(dto.getPersonmobile());
                    }
                    smsService.giveInfoNotifySMS(mobiles, card.getCardholder());
                }

                return WebResult.success().toMap();
            } else {
                return WebResult.failure("银行卡编辑失败,请重新编辑").toMap();
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);;
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: showBankCard()
     * @Description: TODO(获取当前用户的所有银行卡)
     * @author Jerry Chan
     * @date 2016/11/30 17:02
     */
    @ResponseBody
    @RequestMapping(value = "showbankcard", method = RequestMethod.POST)
    public Map<String, Object> showBankCard() {
        try {

            Long userid = privilegeService.getCurrentPrincipalForApp().getUserid();
            QuerySysUserBankCardCondition condition = new QuerySysUserBankCardCondition();
            condition.setUserid(userid);
            List<SysUserBankCard> cards = sysUserBankCardService.findUserBankCardByCondition(condition);
            if (cards.size() > 0) {
                List<BankCard> bankCard = new ArrayList<BankCard>();
                SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                for (SysUserBankCard card : cards) {
                    BankCard bankcard = new BankCard(card.getCardid(), card.getCardholder(), card.getBankcardnumber());
                    bankcard.setUserid(card.getUserid());
                    bankcard.setAccounttype(card.getAccounttype());
                    bankcard.setBankname(card.getBankname());
                    bankcard.setBankcountry(card.getBankcountry());
                    bankcard.setBankofdeposit(card.getBankofdeposit());
                    bankcard.setBankcity(card.getBankcity());
                    bankcard.setBankprovince(card.getBankprovince());
                    bankcard.setPayunionbank(card.getPayunionbank());
                    bankcard.setMobile(card.getMobile());
                    bankcard.setIdcard(card.getIdcard());
                    bankcard.setCreatetime(format.format(card.getCreatetime()));
                    bankcard.setBussinseclearingbank(card.getBussinseclearingbank());
                    bankcard.setClearingcycle(card.getClearingcycle());
                    bankcard.setCardconfirmed(card.getCardconfirmed());
                    bankcard.setCapitalclearingtype(card.getCapitalclearingtype());
                    bankCard.add(bankcard);
                }

                return WebResult.success().put("data", bankCard).toMap();
            } else {
                return WebResult.failure("尚未绑定银行卡").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);;
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: showBankCardState()
     * @Description: TODO(获取当前用户的所有银行卡的审核状态)
     * @author Jerry Chan
     * @date 2016/11/30 17:02
     */
    @ResponseBody
    @RequestMapping(value = "showbankcardstate", method = RequestMethod.POST)
    public Map<String, Object> showBankCardState() {
        try {
            Long userid = privilegeService.getCurrentPrincipalForApp().getUserid();
            QuerySysUserBankCardCondition condition = new QuerySysUserBankCardCondition();
            condition.setUserid(userid);
            List<SysUserBankCard> cards = sysUserBankCardService.findUserBankCardByCondition(condition);
            if (cards.size() > 0) {
                List<VerifyResult> states = new ArrayList<VerifyResult>();
                SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                for (SysUserBankCard card : cards) {
                    VerifyResult result = new VerifyResult();
                    result.setId(card.getCardid());
                    result.setState(card.getCardconfirmed());
                    result.setVerifyContent(card.getComment());
                    result.setVerifyTime(format.format(card.getUpdatetime()));
                    states.add(result);
                }
                return WebResult.success().put("data", states).toMap();
            } else {
                return WebResult.failure("尚未绑定银行卡").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);;
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: bindBankCard
     * @Description: TODO(绑定用户的银行卡)
     * @author Jerry Chan
     * @date 2016/11/30 15:22
     */
    @ResponseBody
    @RequestMapping(value = "bindbankcard", method = RequestMethod.POST)
    public Map<String, Object> bindBankCard(AddBankCardCommand bankCard) {
        try {

            Long userid = privilegeService.getCurrentPrincipalForApp().getUserid();
            QuerySysUserBankCardCondition condition = new QuerySysUserBankCardCondition();
            condition.setUserid(userid);
            if (sysUserBankCardService.findUserBankCardByCondition(condition).size() >= 1) {
                return WebResult.failure("银行卡已经存在，不能绑定多张银行卡").toMap();
            }

            String positiveSaveResult, behindSaveResult, licenseSaveResult = "";

            if (bankCard.getIdcrardimgpositive() != null) {
                //保存身份证正面照
                positiveSaveResult = FileManager
                        .saveImage(bankCard.getIdcrardimgpositive(), Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY);
                if (positiveSaveResult.contains(FileManager.ERRORSTR)) {
                    return WebResult.failure(positiveSaveResult.replace(FileManager.ERRORSTR, "")).toMap();
                }
            } else {
                return WebResult.failure("请上传身份证正面照").toMap();
            }

            if (bankCard.getIdcrardimgbehind() != null) {
                //保存身份证反面照
                behindSaveResult = FileManager
                        .saveImage(bankCard.getIdcrardimgbehind(), Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY);
                if (behindSaveResult.contains(FileManager.ERRORSTR)) {
                    return WebResult.failure(behindSaveResult.replace(FileManager.ERRORSTR, "")).toMap();
                }
            } else {
                return WebResult.failure("请上传身份证反面照").toMap();
            }

            if (bankCard.getBusinesslicense() != null) {
                licenseSaveResult = FileManager
                        .saveImage(bankCard.getBusinesslicense(), Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY);
                if (licenseSaveResult.contains(FileManager.ERRORSTR)) {
                    return WebResult.failure(licenseSaveResult.replace(FileManager.ERRORSTR, "")).toMap();
                }
            }

            SysUserBankCard card = new SysUserBankCard();
            card.setUserid(userid);
            card.setAdminid(userid);
            card.setCardholder(bankCard.getCardholder());
            card.setBankcardnumber(bankCard.getBankcardnumber());
            card.setBankname(bankCard.getBankname());
            card.setMobile(bankCard.getMobile());
            card.setIdcard(bankCard.getIdcard());
            card.setPayunionbank(bankCard.getPayunionbank());
            card.setBankcountry(bankCard.getBankcountry());
            card.setBankprovince(bankCard.getBankprovince());
            card.setBankcity(bankCard.getBankcity());
            card.setBankofdeposit(bankCard.getBankofdeposit());
            card.setAccounttype(bankCard.getAccounttype());
            card.setBussinseclearingbank(bankCard.getBussinseclearingbank());
            card.setClearingcycle(bankCard.getClearingcycle());
            card.setCapitalclearingtype(bankCard.getCapitalclearingtype());
            card.setUpdatetime(new Date());
            card.setIdcrardimgpositive(positiveSaveResult != "" ? Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY + "/" + 
                    positiveSaveResult : null);
            card.setIdcrardimgbehind(behindSaveResult != "" ? Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY + "/" + 
                    behindSaveResult : null);
            card.setBusinesslicense(licenseSaveResult != "" ? Constants.SYSTEM_TMAGE_IDCARD_DIRECTORY + "/" + 
                    licenseSaveResult : null);
            int result = sysUserBankCardService.insertSelective(card);
            if (result > 0) {
                //进件受理通知(给客户)
                smsService.giveInfoAcceptSMS(card.getMobile(), card.getCardholder());
                //进件受理通知(给审核员)
                List<SysAuditPersonDto> personDtos = sysAuditPersonService
                        .findListsByCondition(new QuerySysAuditPersonCondition());
                if (personDtos != null && personDtos.size() > 0) {
                    List<String> mobiles = new ArrayList<String>();
                    for (SysAuditPersonDto dto : personDtos) {
                        mobiles.add(dto.getPersonmobile());
                    }
                    smsService.giveInfoNotifySMS(mobiles, card.getCardholder());
                }

                return WebResult.success().put("data", card.getCardid()).toMap();
            } else {
                return WebResult.failure("绑定银行卡失败").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);;
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: showUserLogo()
     * @Description: TODO(获取用户自定义的Logo)
     * @author Jerry Chan
     * @date 2016/12/1 9:47
     */
    @ResponseBody
    @RequestMapping(value = "showLogo", method = RequestMethod.POST)
    public Map<String, Object> showUserLogo() {
        try {
            Long userid = privilegeService.getCurrentPrincipalForApp().getUserid();
            QuerySysNoticeCondition condition = new QuerySysNoticeCondition();
            condition.setUserid(userid);
            condition.setQueryAll(true);
            List<SysNoticeDto> noticeDtos = sysNoticeService.findListsByCondition(condition);

            if (noticeDtos == null || noticeDtos.size() <= 0) {
                return WebResult.failure("尚未上传Logo").toMap();
            }

            List<String> logourls = new ArrayList<String>();
            for (SysNoticeDto noticeDto : noticeDtos) {
                logourls.add(noticeDto.getLogourl());
            }
            return WebResult.success().put("data", logourls).toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);;
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }

    }

    /**
     * @param logo logo图片
     * @Title: uploadUserLogo
     * @Description: TODO(上传Logo图片)
     * @author Jerry Chen
     * @date 2016年10月22日 上午3:05:21
     */
    @ResponseBody
    @RequestMapping(value = "/uploadLogo", method = RequestMethod.POST)
    public Map<String, Object> uploadUserLogo(@RequestParam(value = "file", required = false) MultipartFile logo) {
        try {

            //logo.transferTo(logofile);
            String logopath = SessionManager.getContext().getRealPath("")
                                            .replace(Constants.SITE_NAME, Constants.SYSTEM_TMAGE_USERLOGO_DIRECTORY);
            String logoSaveResult = FileManager.saveImage(logo, logopath);
            if (logoSaveResult.contains(FileManager.ERRORSTR)) {
                return WebResult.failure(logoSaveResult.replace(FileManager.ERRORSTR, "")).toMap();
            }

            Long userid = privilegeService.getCurrentPrincipalForApp().getUserid();
            SysNotice notice = new SysNotice();
            notice.setLogourl(SessionManager
                    .getWebServerURL() + Constants.SYSTEM_TMAGE_USERLOGO_DIRECTORY + "/" + logoSaveResult);
            notice.setUpdatetime(new Date());
            notice.setAdminid(userid);
            notice.setUserid(userid);

            if (addORUpdateNotice(notice) > 0) {
                return WebResult.success().info("Logo上传成功").put("data", notice.getLogourl()).toMap();
            } else {
                return WebResult.failure("Logo上传失败，请稍后重新上传").toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }


    }

    /**
     * @param oldPassword 原始登录密码
     * @param newPassword 新登录密码
     * @Title: changeLoginPassword
     * @Description: TODO(修改当前用户的登录密码)
     * @author Jerry
     * @date 2016-10-21 12:32:45
     */
    @ResponseBody
    @RequestMapping(value = "/changeloginpassword", method = RequestMethod.POST)
    public Map<String, Object> changeLoginPassword(final @RequestParam String oldPassword, final @RequestParam String
            newPassword/*,
            final @RequestParam String mobliecode*/) {
        try {

           /* Map<String, Object> verifyResult = changePasswordVerify(mobliecode);
            if (verifyResult != null)
                return verifyResult;*/

            if (oldPassword.equals(newPassword)) {
                return WebResult.failure("旧密码与新密码一致").toMap();
            }
            SysUser user = super.findSysUser(privilegeService.getCurrentPrincipalForApp().getUserid());
            if (!QEncodeUtil.md5Encrypt(oldPassword).equals(user.getPassword())) {
                return WebResult.failure("旧密码错误，请重新输入").toMap();
            } else if (QEncodeUtil.md5Encrypt(newPassword).equals(user.getTransferpassword())) {
                return WebResult.failure("旧密码不能与提现密码一致").toMap();
            }

            user.setPassword(QEncodeUtil.md5Encrypt(newPassword));
            super.changePassword(user);

            return WebResult.success().info("旧密码修改成功").toMap();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param oldPassword 原始提现密码
     * @param newPassword 新提现密码
     * @Title: changeTransferPassword
     * @Description: TODO(修改当前用户的提现密码)
     * @author Jerry
     * @date 2016-10-21 12:32:45
     */
    @ResponseBody
    @RequestMapping(value = "/changereansferpassword", method = RequestMethod.POST)
    public Map<String, Object> changeTransferPassword(final @RequestParam String oldPassword, final @RequestParam 
            String newPassword
            /*final @RequestParam String mobliecode*/) {
        try {

            /*Map<String, Object> verifyResult = changePasswordVerify(mobliecode);
            if (verifyResult != null)
                return verifyResult;*/

            if (oldPassword.equals(newPassword)) {
                return WebResult.failure("原始提现密码与新密码一致").toMap();
            }

            SysUser user = findSysUser(privilegeService.getCurrentPrincipalForApp().getUserid());
            if (!QEncodeUtil.md5Encrypt(oldPassword).equals(user.getTransferpassword())) {
                return WebResult.failure("与原始提现密码错误，请重新输入").toMap();
            } else if (QEncodeUtil.md5Encrypt(newPassword).equals(user.getPassword())) {
                return WebResult.failure("提现密码不能与登录密码一致").toMap();
            }

            user.setTransferpassword(QEncodeUtil.md5Encrypt(newPassword));

            sysUserService.changeTransferPassword(user);

            return WebResult.success().info("提现密码修改成功").toMap();


        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param code   短信验证码
     * @param moblie 手机号码
     * @Title: changeUserMoblie
     * @Description: TODO(修改用户手机号码)
     * @author Jerry
     * @date 2016-10-20 07:59:24
     */
    @ResponseBody
    @RequestMapping(value = "/changeMoblie", method = RequestMethod.POST)
    public Map<String, Object> changeUserMoblie(final @RequestParam String code, final @RequestParam String moblie) {
        try {

            VaildPhone vaildPhone = PhoneCodeCacheTimer.get(code);
            if (vaildPhone == null) {
                return WebResult.failure("短信验证码错误，请重新输入").toMap();
            } else if (vaildPhone.getValidTime() < new Date().getTime()) {
                PhoneCodeCacheTimer.remove(code);
                return WebResult.failure("短信验证码过期，请重新获取短信验证码").toMap();
            } else {
                SysUser user = new SysUser();
                user.setMobile(moblie);
                if (sysUserService.findUserByUsername(user) != null) {
                    return WebResult.failure("手机号已被使用，请更换其他手机号码").toMap();
                }

                Long currentUserID = privilegeService.getCurrentPrincipalForApp().getUserid();
                user.setUserid(currentUserID);
                user.setAdminid(currentUserID);
                user.setUpdatetime(new Date());
                sysUserService.updateByPrimaryKeySelective(user);

                PhoneCodeCacheTimer.remove(code);
                return WebResult.success().toMap();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @return UserInfo 当前登录的用户信息
     * @Title: showSeurityView
     * @Description: TODO(我的主界面下的，顶部中“余额”)
     * @author Jerry
     * @date 2016-10-20 07:13:36
     */
    @ResponseBody
    @RequestMapping(value = "/showbalance", method = RequestMethod.POST)
    public Map<String, Object> showUserBalance() {
        try {
            QuerySysUserBalanceCondition querySysUserBalanceCondition = new QuerySysUserBalanceCondition();
            querySysUserBalanceCondition.setUserId(privilegeService.getCurrentPrincipalForApp().getUserid());

            return WebResult.success().put("data", sysUserBalanceService.findByCondition(querySysUserBalanceCondition))
                            .toMap();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);;
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param userid      子账户ID
     * @param newpassword 子账户新密码
     * @return
     * @Title: resetPassword
     * @Description: TODO(重置子账户密码)
     * @author Jerry
     * @date 2016-10-20 03:32:02
     */
    @ResponseBody
    @RequestMapping(value = "/resetChildUserPassword", method = RequestMethod.POST)
    public Map<String, Object> resetPassword(final @RequestParam Long userid, final @RequestParam String newpassword) {

        try {
            SysUser user = new SysUser();

            user.setUserid(userid);
            user.setAdminid(privilegeService.getCurrentPrincipalForApp().getUserid());
            user.setUpdatetime(new Date());
            String password = "";
            if (newpassword == null || "".equals(newpassword)) {

                password = QEncodeUtil.md5Encrypt(Constants.NOTIC_DEFAULT_USER_PASSWORD);

            } else {

                password = QEncodeUtil.md5Encrypt(newpassword);

            }
            user.setPassword(password);

            super.changePassword(user);
            return WebResult.success().toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }

    }

    /**
     * @param roleid 角色ID
     * @Title: showChildUserView
     * @Description: TODO(获取子账户信息)
     * @author Jerry
     * @date 2016-10-20 11:06:36
     */
    @ResponseBody
    @RequestMapping(value = "/showchilduserinfo", method = RequestMethod.POST)
    public Map<String, Object> showChildUserView(Long roleid) {

        QuerySysUserCondition condition = new QuerySysUserCondition();
        condition.setParentid(privilegeService.getCurrentPrincipalForApp().getUserid());
        condition.setRoleid(roleid);

        List<SysUserDto> userDtos = sysUserService.findChildUserByPrientIDAndRoleID(condition);

        if (userDtos != null && userDtos.size() > 0) {
            List<com.leesche.zcsp.node.app.v1.vo.UserInfo> userinfos = new ArrayList<com.leesche.zcsp.node.app.v1.vo
                    .UserInfo>();
            for (SysUserDto dto : userDtos) {
                com.leesche.zcsp.node.app.v1.vo.UserInfo info = new com.leesche.zcsp.node.app.v1.vo.UserInfo(dto
                        .getTextCN(), dto.getUserid(), dto.getEmail(), dto.getUsername(), dto.getMobile(), dto
                        .getProperty(), dto.getRemark(), dto.getCreatetime(), dto.getOuttime());
                userinfos.add(info);
            }
            return WebResult.success().put("data", userinfos).toMap();
        } else {
            return WebResult.failure("该用户组下还没有子账户").toMap();
        }
    }

    /**
     * @Title: showUserGroupView
     * @Description: TODO(获取当前用户下的用户组集合)
     * @author Jerry
     * @date 2016-11-17 12:08:46
     */
    @ResponseBody
    @RequestMapping(value = "/showusergroup", method = RequestMethod.POST)
    public Map<String, Object> showUserGroupView() {
        try {
            List<SysRole> sysRoles = sysRoleService
                    .findChildRoleByBusinessUserID(privilegeService.getCurrentPrincipalForApp().getUserid());

            List<UserGroup> childUserGroups = new ArrayList<UserGroup>();
            for (SysRole sysrole : sysRoles) {
                UserGroup childUserGroup = new UserGroup();
                childUserGroup.setUserGroupid(sysrole.getRoleid());
                childUserGroup.setTextCN(sysrole.getNamecn());
                childUserGroups.add(childUserGroup);
            }
            return WebResult.success().put("data", childUserGroups).toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: showBusinessInfoView
     * @Description: TODO(展示商业用户的信息)
     * @author Jerry
     * @date 2016-10-20 12:47:21
     */
    @ResponseBody
    @RequestMapping(value = "/showbusinessinfo", method = RequestMethod.POST)
    public Map<String, Object> showBusinessInfoView() {
        try {

            SysUser user = super.findSysUser(privilegeService.getCurrentPrincipalForApp().getUserid());
            UserInfo userInfo = new UserInfo(user.getUserid(), user.getBusinessno(), user.getEmail(), user
                    .getUsername(), user.getMobile(), user.getUrl(), user.getRemark(), user.getCreatetime(), user
                    .getOuttime());
            setConfimedState(user, userInfo);

            //return userInfo;
            return WebResult.success().put("data", userInfo).toMap();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }

    }

    /**
     * @param user     用户信息
     * @param userInfo 前台显示的用户信息VO类
     * @Title: setConfimedState
     * @Description: TODO(设置用户的验证状态)
     * @author Jerry
     * @date 2016-11-17 04:28:07
     */
    private void setConfimedState(SysUser user, UserInfo userInfo) {
        String wechatAuthorization = user.getOpenid() == null ? "" : "微信已授权";
        String moblieAuthorization = user.getMobileconfirmed() == 0 ? "" : "手机已认证";
        String emailAuthorization = user.getEmailconfirmed() == 0 ? "" : "邮箱已认证";

        userInfo.setConfirmedState(new String[]{wechatAuthorization, moblieAuthorization, emailAuthorization});
    }

    /**
     * @param SMScode 短信验证码
     * @return 返回 null 表示正常。不为空则是有异常，Controller直接响应客户端即可
     * @Title: changePasswordVerify
     * @Description: TODO(修改密码前验证)
     * @author Jerry
     * @date 2016-10-21 03:28:00
     */
    private Map<String, Object> changePasswordVerify(String SMScode) throws Exception {

        Map<String, Object> result = super.verifySeesionCode();

        if (super.verifyResult == false) {
            return result;
        }

        String sessionCode = result.get(Constants.MOBILE_SMS_CODE).toString();

        SysUser currentUser = super.findSysUser(privilegeService.getCurrentPrincipalForApp().getUserid());

        result = super.verifyMoblieCode(currentUser.getMobile(), SMScode, sessionCode, currentUser.getMobile());

        if (result != null) {
            return result;
        }

        return null;
    }

    /**
     * @return
     * @Title: addCustomerInfo
     * @Description: TODO(完善个人信息)
     * @author Jerry Chan
     * @date 2016-11-17 12:13:01
     */
    @ResponseBody
    @RequestMapping(value = "/submitCustomerInfo", method = RequestMethod.POST)
    public Map<String, Object> addCustomerInfo(final PubCustomer customer) {

        return null;
    }

    /**
     * @return
     * @Title:
     * @Description: TODO(修改个人信息)
     * @author Jerry
     * @date 2016-11-17 12:14:54
     */
    @ResponseBody
    @RequestMapping(value = "/changeCustomerInfo", method = RequestMethod.POST)
    public Map<String, Object> changeCustomerInfo(final PubCustomer customer) {

        return null;
    }

    /**
     * @return 操作结果
     * @Title: addORUpdateNotice(SysNotice notice)
     * @Description: TODO(添加或修改用户公告信息)
     * @author Jerry Chan
     * @date 2016/12/1 17:02
     */
    private int addORUpdateNotice(SysNotice notice) {
        QuerySysNoticeCondition condition = new QuerySysNoticeCondition();
        condition.setUserid(notice.getUserid());
        condition.setQueryAll(true);
        List<SysNoticeDto> noticeDtos = sysNoticeService.findListsByCondition(condition);
        if (noticeDtos.size() > 0) {

            SysNoticeCriteria criteria = new SysNoticeCriteria();
            criteria.or().andUseridEqualTo(notice.getUserid());
            //修改底部文字
            return sysNoticeService.updateByCriteriaSelective(notice, criteria);

        } else {
            // 增加底部文字
            return sysNoticeService.insertSelective(notice);
        }
    }

}
